import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useDocumentStore = defineStore('document', () => {
  // 状态
  const documents = ref([])
  const currentDocument = ref(null)
  const searchResults = ref([])
  const loading = ref(false)
  const searchKeyword = ref('')
  const searchHistory = ref([])

  // 计算属性
  const documentsByType = computed(() => {
    const grouped = {}
    documents.value.forEach(doc => {
      if (!grouped[doc.type]) {
        grouped[doc.type] = []
      }
      grouped[doc.type].push(doc)
    })
    return grouped
  })

  const recentDocuments = computed(() => {
    return documents.value
      .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
      .slice(0, 10)
  })

  const totalDocuments = computed(() => documents.value.length)

  const documentStats = computed(() => {
    const stats = {
      total: documents.value.length,
      pdf: 0,
      docx: 0,
      pptx: 0,
      xlsx: 0,
      image: 0
    }
    
    documents.value.forEach(doc => {
      if (doc.type === 'pdf') stats.pdf++
      else if (doc.type === 'docx') stats.docx++
      else if (doc.type === 'pptx') stats.pptx++
      else if (doc.type === 'xlsx') stats.xlsx++
      else if (['jpg', 'png', 'gif', 'bmp', 'webp'].includes(doc.type)) stats.image++
    })
    
    return stats
  })

  // 方法
  const initializeMockData = () => {
    const mockDocs = [
      // MMC项目相关文档
      {
        id: '1',
        name: 'MMC项目招标宣讲.pdf',
        type: 'pdf',
        size: 2048000,
        path: '/documents/mmc-bidding.pdf',
        thumbnail: null,
        tags: ['MMC', '招标', '项目', '宣讲'],
        description: 'MMC代谢管理中心项目招标宣讲材料',
        author: '项目经理',
        createdAt: '2024-01-15',
        updatedAt: '2024-01-20',
        category: '项目文档',
        status: 'active',
        downloadCount: 25,
        viewCount: 78,
        isFavorite: true
      },
      {
        id: '2',
        name: 'MMC培训测试评分标准.docx',
        type: 'docx',
        size: 768000,
        path: '/documents/mmc-training-standard.docx',
        thumbnail: null,
        tags: ['MMC', '培训', '评分标准', '测试'],
        description: 'MMC项目培训测试的详细评分标准文档',
        author: '培训部',
        createdAt: '2024-01-12',
        updatedAt: '2024-01-18',
        category: '培训资料',
        status: 'active',
        downloadCount: 18,
        viewCount: 42,
        isFavorite: false
      },
      {
        id: '3',
        name: 'MMC考试卷（答案版）.doc',
        type: 'docx',
        size: 512000,
        path: '/documents/mmc-exam-answers.doc',
        thumbnail: null,
        tags: ['MMC', '考试', '答案', '培训'],
        description: 'MMC项目培训考试卷标准答案版本',
        author: '培训部',
        createdAt: '2024-01-10',
        updatedAt: '2024-01-15',
        category: '培训资料',
        status: 'active',
        downloadCount: 15,
        viewCount: 33,
        isFavorite: false
      },
      
      // 医疗设备相关文档
      {
        id: '4',
        name: 'FMD血流检测设备技术方案.pdf',
        type: 'pdf',
        size: 3200000,
        path: '/documents/fmd-technical-plan.pdf',
        thumbnail: null,
        tags: ['FMD', '血流检测', '技术方案', '设备'],
        description: 'FMD血流介导性血管舒张功能检测设备完整技术方案',
        author: '技术部',
        createdAt: '2024-01-08',
        updatedAt: '2024-01-20',
        category: '技术文档',
        status: 'active',
        downloadCount: 12,
        viewCount: 28,
        isFavorite: true
      },
      {
        id: '5',
        name: '欧姆龙血压计HEM-7136产品手册.pdf',
        type: 'pdf',
        size: 1800000,
        path: '/documents/omron-hem7136-manual.pdf',
        thumbnail: null,
        tags: ['欧姆龙', '血压计', 'HEM-7136', '产品手册'],
        description: '欧姆龙HEM-7136血压计详细产品使用手册',
        author: '产品部',
        createdAt: '2024-01-05',
        updatedAt: '2024-01-12',
        category: '产品资料',
        status: 'active',
        downloadCount: 22,
        viewCount: 56,
        isFavorite: false
      },
      {
        id: '6',
        name: '医疗器械培训课件.pptx',
        type: 'pptx',
        size: 4500000,
        path: '/documents/medical-device-training.pptx',
        thumbnail: null,
        tags: ['医疗器械', '培训', '课件', '操作指南'],
        description: '医疗器械操作培训的完整课件PPT',
        author: '培训部',
        createdAt: '2024-01-03',
        updatedAt: '2024-01-10',
        category: '培训资料',
        status: 'active',
        downloadCount: 35,
        viewCount: 89,
        isFavorite: true
      },
      
      // 智众医信相关文档
      {
        id: '7',
        name: '智众医信SaaS平台介绍.pdf',
        type: 'pdf',
        size: 2100000,
        path: '/documents/zhizhong-saas-intro.pdf',
        thumbnail: null,
        tags: ['智众医信', 'SaaS', '平台', '介绍'],
        description: '智众医信SaaS平台功能介绍和技术架构说明',
        author: '合作伙伴',
        createdAt: '2023-12-28',
        updatedAt: '2024-01-08',
        category: '合作文档',
        status: 'active',
        downloadCount: 8,
        viewCount: 19,
        isFavorite: false
      },
      {
        id: '8',
        name: '数字化医院科室管理解决方案.docx',
        type: 'docx',
        size: 1900000,
        path: '/documents/digital-hospital-solution.docx',
        thumbnail: null,
        tags: ['数字化', '医院', '科室管理', '解决方案'],
        description: '数字化医院科室管理系统的完整解决方案',
        author: '解决方案部',
        createdAt: '2023-12-25',
        updatedAt: '2024-01-05',
        category: '解决方案',
        status: 'active',
        downloadCount: 14,
        viewCount: 31,
        isFavorite: false
      },
      
      // 设备采购和技术文档
      {
        id: '9',
        name: '心血管检测设备采购清单.xlsx',
        type: 'xlsx',
        size: 650000,
        path: '/documents/cardiovascular-equipment-list.xlsx',
        thumbnail: null,
        tags: ['心血管', '检测设备', '采购', '清单'],
        description: '心血管相关检测设备的详细采购清单和规格要求',
        author: '采购部',
        createdAt: '2023-12-20',
        updatedAt: '2024-01-02',
        category: '采购文档',
        status: 'active',
        downloadCount: 11,
        viewCount: 24,
        isFavorite: false
      },
      {
        id: '10',
        name: '呼吸检测设备技术参数对比.xlsx',
        type: 'xlsx',
        size: 890000,
        path: '/documents/respiratory-device-comparison.xlsx',
        thumbnail: null,
        tags: ['呼吸检测', '设备', '技术参数', '对比'],
        description: '各品牌呼吸检测设备的技术参数详细对比分析',
        author: '技术部',
        createdAt: '2023-12-15',
        updatedAt: '2023-12-28',
        category: '技术文档',
        status: 'active',
        downloadCount: 7,
        viewCount: 16,
        isFavorite: false
      },
      
      // 代谢检测相关文档
      {
        id: '11',
        name: '代谢检测设备使用手册.pdf',
        type: 'pdf',
        size: 2800000,
        path: '/documents/metabolism-device-manual.pdf',
        thumbnail: null,
        tags: ['代谢检测', '设备', '使用手册', '操作指南'],
        description: '代谢相关检测设备的完整使用手册和操作指南',
        author: '技术部',
        createdAt: '2023-12-10',
        updatedAt: '2023-12-25',
        category: '技术文档',
        status: 'active',
        downloadCount: 16,
        viewCount: 39,
        isFavorite: true
      },
      {
        id: '12',
        name: '国家标准化代谢管理中心建设方案.pptx',
        type: 'pptx',
        size: 5200000,
        path: '/documents/national-mmc-construction.pptx',
        thumbnail: null,
        tags: ['国家标准', '代谢管理', '中心建设', 'MMC'],
        description: '国家标准化代谢管理中心(MMC)的完整建设方案',
        author: '项目经理',
        createdAt: '2023-12-05',
        updatedAt: '2023-12-22',
        category: '项目文档',
        status: 'active',
        downloadCount: 28,
        viewCount: 72,
        isFavorite: true
      },
      
      // 济南闰凯相关文档
      {
        id: '13',
        name: '济南闰凯医疗器械产品目录.pdf',
        type: 'pdf',
        size: 1600000,
        path: '/documents/jinan-runkai-catalog.pdf',
        thumbnail: null,
        tags: ['济南闰凯', '医疗器械', '产品目录', '呼吸系统'],
        description: '济南闰凯医疗器械有限公司呼吸系统产品完整目录',
        author: '合作伙伴',
        createdAt: '2023-11-28',
        updatedAt: '2023-12-15',
        category: '合作文档',
        status: 'active',
        downloadCount: 9,
        viewCount: 21,
        isFavorite: false
      },
      {
        id: '14',
        name: '肺功能检测设备技术培训资料.pdf',
        type: 'pdf',
        size: 3100000,
        path: '/documents/pulmonary-function-training.pdf',
        thumbnail: null,
        tags: ['肺功能', '检测设备', '技术培训', '呼吸系统'],
        description: '肺功能检测设备的技术培训资料和操作规范',
        author: '培训部',
        createdAt: '2023-11-25',
        updatedAt: '2023-12-10',
        category: '培训资料',
        status: 'active',
        downloadCount: 13,
        viewCount: 35,
        isFavorite: false
      },
      
      // 投标和商务文档
      {
        id: '15',
        name: '医院信息化项目投标书.doc',
        type: 'docx',
        size: 2400000,
        path: '/documents/hospital-it-bidding.doc',
        thumbnail: null,
        tags: ['医院', '信息化', '投标书', '项目'],
        description: '医院信息化建设项目的完整投标文件',
        author: '商务部',
        createdAt: '2023-11-20',
        updatedAt: '2023-12-05',
        category: '商务文档',
        status: 'active',
        downloadCount: 6,
        viewCount: 14,
        isFavorite: false
      },
      {
        id: '16',
        name: '设备维护保养服务协议.pdf',
        type: 'pdf',
        size: 980000,
        path: '/documents/equipment-maintenance-agreement.pdf',
        thumbnail: null,
        tags: ['设备维护', '保养', '服务协议', '合同'],
        description: '医疗设备维护保养服务的标准协议模板',
        author: '法务部',
        createdAt: '2023-11-15',
        updatedAt: '2023-11-30',
        category: '合同文档',
        status: 'active',
        downloadCount: 12,
        viewCount: 27,
        isFavorite: false
      }
    ]
    
    documents.value = mockDocs
  }

  // 从 public/files-manifest.json 加载外部清单并合并为数据源之一
  const loadFromManifest = async () => {
    try {
      const response = await fetch('/files-manifest.json', { cache: 'no-cache' })
      if (!response.ok) return
      const manifest = await response.json()

      // 类型映射，兼容杂乱扩展名
      const typeAlias = {
        doc: 'docx',
        ppt: 'pptx',
        xls: 'xlsx',
        jpeg: 'jpg',
        tif: 'tif',
        tiff: 'tif'
      }

      const mapType = (ext) => {
        const lower = String(ext || '').toLowerCase()
        return typeAlias[lower] || lower
      }

      const normalized = Array.isArray(manifest) ? manifest.map((rec) => ({
        id: String(rec.id || rec.path || Date.now().toString()),
        name: rec.name || '未命名',
        type: mapType(rec.type),
        size: rec.size || 0,
        path: rec.path || '',
        thumbnail: rec.thumbnail || null,
        tags: Array.isArray(rec.tags) ? rec.tags : [],
        description: rec.description || '',
        author: rec.author || '',
        createdAt: rec.createdAt || new Date().toISOString(),
        updatedAt: rec.updatedAt || new Date().toISOString(),
        category: rec.category || '',
        status: 'active',
        downloadCount: rec.downloadCount || 0,
        viewCount: rec.viewCount || 0,
        isFavorite: !!rec.isFavorite
      })) : []

      // 去重合并：以 path 为主键避免重复
      const existingPaths = new Set(documents.value.map(d => d.path))
      normalized.forEach((doc) => {
        if (!doc.path || existingPaths.has(doc.path)) return
        documents.value.push(doc)
        existingPaths.add(doc.path)
      })
    } catch (err) {
      // 静默失败：外部数据源不可用时不影响原型使用
      console.warn('loadFromManifest failed', err)
    }
  }

  const searchDocuments = (keyword, filters = {}) => {
    loading.value = true
    searchKeyword.value = keyword
    
    // 模拟搜索延迟
    setTimeout(() => {
      let results = documents.value
      
      // 关键词筛选
      if (keyword && keyword.trim()) {
        const searchTerm = keyword.toLowerCase()
        results = results.filter(doc => 
          doc.name.toLowerCase().includes(searchTerm) ||
          doc.description.toLowerCase().includes(searchTerm) ||
          doc.tags.some(tag => tag.toLowerCase().includes(searchTerm)) ||
          doc.author.toLowerCase().includes(searchTerm)
        )
      }
      
      // 类型筛选
      if (filters.types && filters.types.length > 0) {
        results = results.filter(doc => filters.types.includes(doc.type))
      }
      
      // 项目筛选
      if (filters.projects && filters.projects.length > 0) {
        results = results.filter(doc => 
          filters.projects.some(project => doc.tags.includes(project))
        )
      }
      
      // 时间范围筛选
      if (filters.timeRange && filters.timeRange !== 'all') {
        const now = new Date()
        const filterDate = new Date()
        
        switch (filters.timeRange) {
          case 'today':
            filterDate.setHours(0, 0, 0, 0)
            break
          case 'week':
            filterDate.setDate(now.getDate() - 7)
            break
          case 'month':
            filterDate.setMonth(now.getMonth() - 1)
            break
          case 'year':
            filterDate.setFullYear(now.getFullYear() - 1)
            break
        }
        
        results = results.filter(doc => new Date(doc.updatedAt) >= filterDate)
      }
      
      // 按相关性和时间排序
      results.sort((a, b) => {
        if (keyword && keyword.trim()) {
          const aRelevance = calculateRelevance(a, keyword)
          const bRelevance = calculateRelevance(b, keyword)
          if (aRelevance !== bRelevance) {
            return bRelevance - aRelevance
          }
        }
        return new Date(b.updatedAt) - new Date(a.updatedAt)
      })
      
      searchResults.value = results
      loading.value = false
    }, 300)
  }

  const calculateRelevance = (doc, keyword) => {
    const searchTerm = keyword.toLowerCase()
    let score = 0
    
    // 标题匹配权重最高
    if (doc.name.toLowerCase().includes(searchTerm)) score += 10
    
    // 标签匹配
    doc.tags.forEach(tag => {
      if (tag.toLowerCase().includes(searchTerm)) score += 5
    })
    
    // 描述匹配
    if (doc.description.toLowerCase().includes(searchTerm)) score += 3
    
    // 作者匹配
    if (doc.author.toLowerCase().includes(searchTerm)) score += 2
    
    // 使用频率加成
    score += Math.log((doc.viewCount || 0) + 1)
    
    return score
  }

  const getDocumentById = (id) => {
    return documents.value.find(doc => doc.id === id)
  }

  const addDocument = (document) => {
    const newDoc = {
      ...document,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      viewCount: 0,
      downloadCount: 0,
      isFavorite: false
    }
    documents.value.unshift(newDoc)
    return newDoc
  }

  const updateDocument = (id, updates) => {
    const index = documents.value.findIndex(doc => doc.id === id)
    if (index !== -1) {
      documents.value[index] = {
        ...documents.value[index],
        ...updates,
        updatedAt: new Date().toISOString()
      }
    }
  }

  const deleteDocument = (id) => {
    const index = documents.value.findIndex(doc => doc.id === id)
    if (index !== -1) {
      documents.value.splice(index, 1)
    }
  }

  const addToHistory = (document) => {
    // 记录访问历史
    document.viewCount = (document.viewCount || 0) + 1
    document.lastAccessed = new Date().toISOString()
  }

  const addSearchHistory = (keyword) => {
    if (!searchHistory.value.includes(keyword)) {
      searchHistory.value.unshift(keyword)
      if (searchHistory.value.length > 10) {
        searchHistory.value.pop()
      }
    }
  }

  return {
    // 状态
    documents,
    currentDocument,
    searchResults,
    loading,
    searchKeyword,
    searchHistory,
    
    // 计算属性
    documentsByType,
    recentDocuments,
    totalDocuments,
    documentStats,
    
    // 方法
    initializeMockData,
    loadFromManifest,
    searchDocuments,
    getDocumentById,
    addDocument,
    updateDocument,
    deleteDocument,
    addToHistory,
    addSearchHistory
  }
})